package cn.orz.study.config;

import com.google.common.util.concurrent.ListenableFutureTask;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author LHL
 * Created by 2020/11/16
 * Description
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Bean
    @Primary
    public static ThreadPoolTaskExecutor threadPoolTaskExecutor(){

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors()*2);
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*2);
        executor.setThreadNamePrefix("mzmz-thread-pool");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.afterPropertiesSet();
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @SneakyThrows
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                log.warn("Task {} rejected from {}", r.toString(), executor.toString());
                ListenableFutureTask task = ListenableFutureTask.create(r, null);
                task.get();
            }
        });
        return executor;
    }




}
